import { defineStore } from 'pinia'
import { userApi } from '@/api'

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartList: [], // 购物车列表
    totalCount: 0, // 总数量
    totalPrice: 0, // 总价格
    loading: false // 加载状态
  }),
  
  getters: {
    getCartList: (state) => state.cartList,
    getTotalCount: (state) => state.totalCount,
    getTotalPrice: (state) => state.totalPrice,
    getLoading: (state) => state.loading
  },
  
  actions: {
    // 从服务器获取购物车数据
    async fetchCartList() {
      if (this.loading) return
      try {
        this.loading = true
        const data = await userApi.getCart()
        if (Array.isArray(data)) {
          // 转换数据结构
          this.cartList = data.map(item => ({
            id: item.id,
            productId: item.productId,
            name: item.productName,
            image: item.image,
            price: item.price,
            quantity: item.quantity,
            selected: item.selected === 1, // 0未选中，1已选中
            status: item.status, // '0'正常，'1'已下架
            specText: item.specSnapshot ? JSON.parse(item.specSnapshot).map(spec => spec.value).join('/') : ''
          }))
          this.calculateTotal()
        }
      } catch (error) {
        console.error('获取购物车数据失败:', error)
        uni.showToast({
          title: '获取购物车数据失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 更新购物车列表
    updateCartList(list) {
      this.cartList = list
      this.calculateTotal()
    },
    
    // 添加商品到购物车
    addToCart(goods) {
      const index = this.cartList.findIndex(item => 
        item.productId === goods.productId && 
        item.skuId === goods.skuId
      )
      
      if (index > -1) {
        // 商品已存在，增加数量
        this.cartList[index].quantity += goods.quantity
      } else {
        // 新商品，添加到列表
        this.cartList.push(goods)
      }
      
      this.calculateTotal()
    },
    
    // 从购物车移除商品
    removeFromCart(goods) {
      const index = this.cartList.findIndex(item => 
        item.productId === goods.productId && 
        item.skuId === goods.skuId
      )
      
      if (index > -1) {
        this.cartList.splice(index, 1)
        this.calculateTotal()
      }
    },
    
    // 更新商品数量
    async updateGoodsQuantity(id, quantity) {
      try {
        // 调用接口更新数量
        await userApi.updateCart(id, { quantity })
        
        // 更新本地状态
        const index = this.cartList.findIndex(item => item.id === id)
        if (index > -1) {
          this.cartList[index].quantity = quantity
          this.calculateTotal()
        }
      } catch (error) {
        console.error('更新商品数量失败:', error)
        uni.showToast({
          title: '更新商品数量失败',
          icon: 'none'
        })
        // 更新失败，重新获取购物车数据
        await this.fetchCartList()
        throw error
      }
    },
    
    // 计算总数和总价
    calculateTotal() {
      this.totalCount = this.cartList.reduce((total, item) => total + item.quantity, 0)
      this.totalPrice = this.cartList
        .filter(item => item.selected && item.status === '0')
        .reduce((total, item) => total + item.price * item.quantity, 0)
    },
    
    // 清空购物车
    clearCart() {
      this.cartList = []
      this.calculateTotal()
    },

    // 删除购物车商品
    async deleteCartItem(id) {
      try {
        // 调用接口删除商品
        await userApi.deleteCart(id)
        
        // 更新本地状态
        const index = this.cartList.findIndex(item => item.id === id)
        if (index > -1) {
          this.cartList.splice(index, 1)
          this.calculateTotal()
        }
      } catch (error) {
        console.error('删除商品失败:', error)
        uni.showToast({
          title: '删除商品失败',
          icon: 'none'
        })
        // 删除失败，重新获取购物车数据
        await this.fetchCartList()
        throw error
      }
    }
  }
}) 